package grimbo.goodwinfooty.server.fileupload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.fileupload.FileItem;

public class MemoryFileItem implements FileItem {
	private boolean isFormField;
	private boolean isInMemory;
	private int size;
	private String fieldName;
	private String fileName;
	private String contentType;
	private ByteArrayOutputStream baos;

	public MemoryFileItem(String fieldName, String contentType,
			boolean isFormField, String fileName) {
		this.fieldName = fieldName;
		this.contentType = contentType;
		this.isFormField = isFormField;
		this.fileName = fileName;
	}

	@Override
	public void write(File file) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public void setFormField(boolean state) {
		this.isFormField = state;
	}

	@Override
	public void setFieldName(String name) {
		this.fieldName = name;
	}

	@Override
	public boolean isInMemory() {
		return this.isInMemory;
	}

	@Override
	public boolean isFormField() {
		return this.isFormField;
	}

	@Override
	public String getString(String encoding)
			throws UnsupportedEncodingException {
		return baos.toString(encoding);
	}

	@Override
	public String getString() {
		return baos.toString();
	}

	@Override
	public long getSize() {
		return baos.size();
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		if (null == baos) {
			baos = new ByteArrayOutputStream();
		}
		return baos;
	}

	@Override
	public String getName() {
		return this.fileName;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return new ByteArrayInputStream(baos.toByteArray());
	}

	@Override
	public String getFieldName() {
		return this.fieldName;
	}

	@Override
	public String getContentType() {
		return this.contentType;
	}

	@Override
	public byte[] get() {
		return baos.toByteArray();
	}

	@Override
	public void delete() {
		throw new UnsupportedOperationException();
	}
}
